package com.jule.miaozhuapc.webSocket.WawaS1Socket;

import com.jule.miaozhuapc.domain.WawaRoom;
import com.jule.miaozhuapc.service.RoomService;
import com.jule.miaozhuapc.webSocket.WawaControl;
import com.jule.miaozhuapc.webSocket.WebSocketSendMessageUtil;
import com.jule.miaozhuapc.webSocket.control.GameUserBean;
import com.jule.miaozhuapc.webSocket.control.WawaControlWebSocket;
import com.jule.miaozhuapc.webSocket.server.WawaServerGameOverCallback;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class S1ThreadReader extends Thread {

    private Logger logger = Logger.getLogger(S1ThreadReader.class);
    @Autowired
    RoomService roomService;

    Socket socket;
    // 房间号
    Integer roomId;

    public S1ThreadReader(Socket socket, Integer roomId) {
        this.socket = socket;
        this.roomId = roomId;
    }

    @Override
    public void run() {
        //socket.isConnected() && !socket.isClosed() && !socket.isInputShutdown()
        while (true) {
            try {
                // 接收数据
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str = null;

                List<Byte> input = new ArrayList<Byte>();
                byte[] buff = new byte[1];
                while ((is.read(buff)) > 0) {
                    byte b = buff[0];
                    input.add(b);
                    if (b == (byte) '\n') {
                        break;
                    }
                }
                byte[] buffer = new byte[input.size()];
                int i = 0;
                for (byte b : input) {
                    buffer[i++] = b;
                }
                str = new String(buffer).trim();
                logger.info("S1服务器输出流数据：[" + str + "]");

                if (str.contains("CONNECT")) {
                    logger.info("连接成功 " + socket.getPort());

                }
                if (str.contains("#")) {


                    if (!(roomId == null || !WawaControlWebSocket.PlayData.containsKey(roomId) || WawaControlWebSocket.PlayData.get(roomId) == null)) {

                        GameUserBean gameUser = WawaControlWebSocket.PlayData.get(roomId);

                        if (str.contains("NOMONEY") || str.contains("NOTAVAILABLE")) {
                            //开始游戏失败
                            new WebSocketSendMessageUtil(WawaControl.NOTAVAILABLE).sendOne(gameUser.getSession());
                            // 清空改房间 FIXME
                            WawaControlWebSocket.PlayData.remove(roomId);

                        } else if (str.contains("AVAILABLE")) {
                            // 开始游戏成功
                            new WebSocketSendMessageUtil(WawaControl.AVAILABLE).setData(gameUser.getCoin()).sendOne(gameUser.getSession());
                            // 房间游戏者
                            new WebSocketSendMessageUtil(WawaControl.PLAYER).setData(gameUser.getWxPic()).sendOne(gameUser.getSession());
                            //给其它用户发送不能开始游戏
                            new WebSocketSendMessageUtil(WawaControl.CANNOTSTART).excludeSession(gameUser.getSession()).sendList(WawaControlWebSocket.seeDatas.get(roomId));
                        } else if (str.contains("CANSTART")) {
                            // 房间空闲

                        } else if (str.contains("CANNOTSTART")) {
                            // 房间不空闲

                        } else if (str.contains("SUCCESS") || str.contains("END")) {
                            // 游戏成功
                            new WawaServerGameOverCallback(roomId, str.replaceAll("#", "")).GameOver();
                            //移除

                        } else {

                        }
                    }
                }
            } catch (Exception e) {
                //
                e.printStackTrace();
                try {
                    socket.getInputStream().close();
                    socket.getOutputStream().close();
                    socket.close();
                    socket = null;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                break;
            }
        }

        //异常 从新建立连接
        // 注入 roomService
        logger.info("---------------------------------------------------------------------" );
        logger.info("发送异常从新建立连接 roomId" + roomId);
        logger.info("---------------------------------------------------------------------" );
        // 模拟 用户与wawa服务器1进行通信
        final Long wawaS1UserId = 27L;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                do {
                    try {
                        socket = new Socket("likewawa.com", 10201);
                        //对象
                        S1SocketUser s1SocketUser = new S1SocketUser();
                        s1SocketUser.setS1UserId(wawaS1UserId);
                        s1SocketUser.setSocket(socket);
                        WawaControlWebSocket.RoomSocketUser.put(roomId, s1SocketUser);
                        //移除房间正在使用用户
                        WawaControlWebSocket.PlayData.put(roomId, null);

                        // 建立输入流连接
                        new S1ThreadReader(socket, roomId).start();
                        logger.info("---------------------------------------------------------------------" );
                        logger.info("发送异常从新建立连接 成功 roomId" + roomId);
                        logger.info("---------------------------------------------------------------------" );
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                        try {
                            Thread.sleep(1000 * 60 * 60*1);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                } while (socket == null);
            }
        }).start();
    }
}